<template>
	<div>
		<!--菜单导航-->
		<el-breadcrumb separator-class="el-icon-arrow-right">
			<el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
			<el-breadcrumb-item>角色管理</el-breadcrumb-item>
			<el-breadcrumb-item>角色列表</el-breadcrumb-item>
		</el-breadcrumb>
		<!-- 内容卡片 -->
		<el-card class="box-card" style="opacity: 0.8;">
			<!-- 搜索框 -->
			<el-row :gutter="20">
				<el-col :span="6">
					<el-input placeholder="请输入内容" @clear="getRoles" clearable v-model="queryRole.rolename"
						class="input-with-select">
						<el-button slot="append" @click="getRoles" icon="el-icon-search"></el-button>
					</el-input>
				</el-col>
				<el-col :span="4">
					<el-button type="primary">添加角色</el-button>
				</el-col>
			</el-row>

			<!-- 数据表格 -->
			<el-table :data="roles" border style="width: 100%">
				<el-table-column type="expand">
					<template slot-scope="scope">
						<!-- 渲染一级分类 -->
						<el-row :key="index"
							style="display:flex;align-items:center;border-bottom: 0px solid #DCDCDC;margin-top: 15px; margin-left: 30px;"
							v-for="(ch,index) in scope.row.children">
							<el-col :span="6">
								<el-tag closable>{{ch.powername}}</el-tag>
								<i class="el-icon-caret-right"></i>
							</el-col>
							<el-col :span="18">
								<!-- 渲染二级分类 -->
								<el-row v-for="er in ch.children" :key="er.powerid"
									style="border-bottom: 0px solid #DCDCDC;margin-top: 10px;">
									<el-col :span="6">
										<el-tag closable type="success">{{er.powername}}</el-tag>
										<i class="el-icon-caret-right"></i>
									</el-col>
								</el-row>
							</el-col>
						</el-row>

					</template>
				</el-table-column>
				<el-table-column type="index" label="#"></el-table-column>
				<el-table-column prop="rolename" label="角色名称">
				</el-table-column>
				<el-table-column prop="roledesc" label="角色备注">
				</el-table-column>
				<el-table-column label="操作">
					<template slot-scope="scope">
						<el-button type="primary" icon="el-icon-edit" size="mini"  @click="toupdate(scope.row.roleid)"></el-button>
						<el-button type="danger" icon="el-icon-delete" size="mini" @click="toDeleteRole(scope.row.roleid)"></el-button>
						<el-tooltip class="item" :enterable="false" effect="dark" content="分配权限" placement="top">
							<el-button type="warning" @click="torole(scope.row)" icon="el-icon-star-off" size="mini">
							</el-button>
						</el-tooltip>
					</template>
				</el-table-column>
			</el-table>

			<!-- 分页展示 -->
			<el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
				:current-page="queryRole.pagenum" :page-sizes="[1, 2, 3, 10]" :page-size="queryRole.pagesize"
				layout="total, sizes, prev, pager, next, jumper" :total="total">
			</el-pagination>
		</el-card>

		<!-- 修改权限的对话框 -->
		<el-dialog title="分配权限" :visible.sync="roledialogVisible" width="50%" :before-close="handleClose">
			<!-- 权限的树形结构 
			:data：数据
			node-key：唯一的标识
			default-expanded-keys：默认展开的树形结构
			default-checked-keys：默认被选中的结构
			props：对数据进行规则展示
		  -->
			<el-tree ref="treeRef" :data="powers" show-checkbox node-key="powerid" :default-expand-all="true"
				:default-checked-keys="checkedids" :props="defaultProps">
				
			</el-tree>

			<span slot="footer" class="dialog-footer">
				<el-button @click="roledialogVisible = false">取 消</el-button>
				<el-button type="primary" @click="updatePower">确 定</el-button>
			</span>
		</el-dialog>
		
		<el-dialog
		        title="修改角色信息"
		        :visible.sync="updateDialogVisible"
		        width="50%"
		        :before-close="updatereset"
		      >
		        <el-form
		          :model="updaterole"
		          ref="updateroleRef"
		          :rules="addRule"
		          label-width="80px"
		        >
		          <el-form-item label="角色名" prop="rolename">
		            <el-input v-model="updaterole.rolename"></el-input>
		          </el-form-item>
		          <el-form-item label="角色描述" prop="roledesc">
		            <el-input v-model="updaterole.roledesc"></el-input>
		          </el-form-item>
		        </el-form>
		            
		        <!-- 取消和添加按钮 -->
		        <span slot="footer" class="dialog-footer">
		          <el-button @click="updatereset">取 消</el-button>
		          <el-button type="primary" @click="updateroleForm">确 定</el-button>
		        </span>
		      </el-dialog>
	</div>
</template>

<script>
	import qs from 'qs'
	export default {
		data() {
			return {
				updateDialogVisible: false,
				      updaterole: {
				          roleid:'',
				        rolename: "",
				        roledesc: "",
				      },
				// 模糊分页查询对象
				queryRole: {
					rolename: '',
					pagenum: 1,
					pagesize: 3
				},
				// 角色列表集合
				roles: [],
				total: 0,
				// 修改权限的对话框
				roledialogVisible: false,
				// 所有的权限列表
				powers: [],
				defaultProps: {
					// 数据展示的下一层树形结构
					children: 'children',
					// 树形结构展示的内容
					label: 'powername'
				},
				// 默认被选中的编号都是最底层的编号
				checkedids: [],
				// 要修改的角色的编号
				rid:0

			}
		},
		methods: {
			   updatereset() {
			      this.updateDialogVisible = false;
			      this.$refs.updateroleRef.resetFields();
			    },
			  async toupdate(id) {
			      var res = await this.$http.get("selectByRoleid?id=" + id);
			      if (res.data.code == 200) {
			        this.updaterole = res.data.data;
			        this.updateDialogVisible = true;
			      } else {
			        this.$message.info(res.data.message);
			      }
			    },
			    updateroleForm(){
			        this.$refs.updateroleRef.validate(async (val) => {
			        if (val) {
			             var param = new URLSearchParams();
			          param.append("roleid", this.updaterole.roleid);
			           param.append("rolename", this.updaterole.rolename);
			           param.append("roledesc", this.updaterole.roledesc);
			           param.append("roleisdel", 0);
			          var res = await this.$http.post(
			            "updateById",
			           param
			          );
			          if (res.data.code == "200") {
			            this.$message.success(res.data.message);
			            this.getRoles();
			          } else {
			            this.$message.error(res.data.message);
			          }
			
			          this.updatereset();
			        } else {
			          this.$message.error("数据不合法，请检查");
			        }
			      });
			    },
			// 模糊分页查询
			async getRoles() {
				var res = await this.$http.post("selectRolesByName", qs.stringify(this.queryRole))
				if (res.data.code == 200) {
					this.roles = res.data.data.list;
					this.total = res.data.data.total;
				} else {
					this.$message.error(res.data.message)
				}
			},
			//每页显示条数改变的函数
			handleSizeChange(npagesize) {
				this.queryRole.pagenum = 1
				this.queryRole.pagesize = npagesize;
				this.getRoles()
			},
			// 访问页码改变的函数
			handleCurrentChange(npagenum) {
				this.queryRole.pagenum = npagenum;
				this.getRoles()
			},
			// 进入为角色分配权限的对话框
			async torole(role) {
				this.rid = role.roleid;
				this.checkedids = [];
				this.roledialogVisible = true;
				var res = await this.$http.post("selectOneTwoPower");
				if (res.data.code == 200) {
					this.powers = res.data.data;
					console.log(res.data.data)
					// 遍历当前角色下的所有权限，取其二级菜单的编号放入到checkedids数组中即可
					for (var i = 0; i < role.children.length; i++) {
						var one = role.children[i];
						for (var j = 0; j < one.children.length; j++) {
							var two = one.children[j];
							// 把当前角色拥有的二级权限编号放入到checkedids中
							console.log('**two**'+two.powerid+two.powername);
							this.checkedids.push(two.powerid)
						}
					}
				} else {
					this.$message.error('查询失败')
				}
			},
			async toDeleteRole(roleid){
				var res = await this.$http.get("deleteRoel?roleid="+roleid)
				if(res.data.code==200){
					this.$message.success(res.data.message)
				}else{
					this.$message.error(res.data.message)
				}
				this.queryRole.pagenum = 1
				this.getRoles()
			},
			handleClose() {
				this.checkedids = []; //清空旧数据
				this.roledialogVisible = false;
			},
			// 提交修改后的权限
			async updatePower(){
				// 修改之后关闭对话框
				this.roledialogVisible = false;
				// 获取修改的被选中的权限的编号及选中的权限的编号
				var keys=[
					...this.$refs.treeRef.getCheckedKeys(),
					...this.$refs.treeRef.getHalfCheckedKeys(),
				];
				// 调用后端的接口，把当前角色的编号和被选中权限的编号传给后端处理即可
				var res = await this.$http.get("updateRolePower?rid="+this.rid+"&pids="+keys.join(','))
				console.log(keys)
				if(res.data.code==200){
					this.$message.success(res.data.message)
					this.getRoles()
				}else{
					this.$message.error(res.data.message)
				}
			}
		},
		// 当前页面加载前执行的代码
		mounted() {
			this.getRoles()
		}
	}
</script>

<style scoped>
</style>
